﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;

public partial class OrderManagement_Order_List_View : PageBase
{
    private const string NEW_PAGE = "Customer_Select.aspx";
    private static string customerid = "";
    private OrgainzationManager orgManager = new OrgainzationManager();
    public string userID
    {
        get { return Request["loginid"] == null ? "" : Request["loginid"].ToString(); }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridPager1.GridView = gvChannelType;
            GridPager1.CurrentPage = PageIndex;
            DataBind();
            if (txtHidOrg.Value == "")
            {
                this.txtHidOrg.Value = OrgHidValue;
                this.txtOrg.Text = OrgShowValue;
                OrgHelper.BindChiansDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlChains);
                //ddlUser.DataSource = new PersonManager().LoadPersons(MyStateManager.OrgID, true, MyStateManager.PersonID.ToString());
                //ddlUser.DataTextField = "Name";
                //ddlUser.DataValueField = "ID";
                OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlUser,MyStateManager.PersonID.ToString());
                //var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
                //if (data.Rows.Count != 1)
                //{
                //    OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlUser);
                //}
                //else
                //{
                //    Person person = new PersonManager().Load(MyStateManager.PersonID);
                //    ddlUser.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
                //}

            }
            InitForm();
            txtEnd.Text = DateTime.Now.ToShortDateString();
            txtStart.Text = DateTime.Now.AddDays(-10).ToShortDateString();
            InitConditionByUrl();
            LoadConditions();
            BindGrid();
            
        }
    }
    protected void InitConditionByUrl()
    {

        if (Request.QueryString["userid"] != null)
        {
            this.ddlUser.SelectedIndex = ddlUser.Items.IndexOf(ddlUser.Items.FindByValue(Request.QueryString["userid"].ToString()));
        }
        DateTime dt = new DateTime();
        if (Request.QueryString["visittime"] != "" &&
            DateTime.TryParse(Request.QueryString["visittime"], out dt))
        {
            this.txtStart.Text = dt.ToShortDateString();
            this.txtEnd.Text = dt.ToShortDateString();
        }
        /////////
        //用于URL跳转后的查找准确的用户
        /////////
        if (Request.QueryString["customerid"] != null)
        {
            customerid = " AND C.ID=" + Request.QueryString["customerid"] + " ";
        }
    }
    private void InitForm()
    {
        DictionaryItemsManager dim = new DictionaryItemsManager();

        //销售渠道
        ddlChannel.DataTextField = "Name";
        ddlChannel.DataValueField = "DictionaryItemId";
        ddlChannel.DataSource = dim.GetItemList(DictionaryEnum.CustomerChannel, this.MyStateManager.DomainID);
        ddlChannel.DataBind();
        ddlChannel.Items.Insert(0, new ListItem("-所有-", ""));

        //绑定订单状态
        string[] names = Enum.GetNames(typeof(Jumpton.SFA.Server.Entity.EOderStatus));
        int[] values = (int[])Enum.GetValues(typeof(Jumpton.SFA.Server.Entity.EOderStatus));
        for (int i = 0; i < names.Length; i++)
        {
            ddlStatus.Items.Add(new ListItem(names[i], values[i].ToString()));
        }
        ddlStatus.Items.Insert(0, new ListItem("--所有--", ""));

        //绑定订单来源
        ddlOrderForm.DataTextField = "Name";
        ddlOrderForm.DataValueField = "DictionaryItemId";
        ddlOrderForm.DataSource = dim.GetItemList(DictionaryEnum.OrderForm, this.MyStateManager.DomainID);
        ddlOrderForm.DataBind();
        ddlOrderForm.Items.Insert(0, new ListItem("手机上传", "0"));
        ddlOrderForm.Items.Insert(0, new ListItem("-所有-", ""));

        //绑定订单类型
        ddlOrderType.DataTextField = "Name";
        ddlOrderType.DataValueField = "CODE";
        ddlOrderType.DataSource = dim.GetItemList(DictionaryEnum.OrderType, this.MyStateManager.DomainID);
        ddlOrderType.DataBind();
        ddlOrderType.Items.Insert(0, new ListItem("-所有-", ""));
       
        USER_CHAINS userChains = new UserManager().LoadChainsByUser(MyStateManager.UserID);

        //经销商用户
        if (userChains != null)
        {
            txtOrg.Text = new OrgainzationManager().Load(MyStateManager.OrgID).NAME;
            txtHidOrg.Value = "'" + MyStateManager.OrgID + "'";
            OrgHelper.BindChiansDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlChains);
            ddlChains.SelectedValue = userChains.CHAINSID.ToString();
            ddlChains.Enabled = false;
            OrgHelper.BindUsersDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlUser);
        }
    }

    private void BindGrid()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder(" ");

        if (!string.IsNullOrEmpty(txtHidOrg.Value))
        {
            sb.Append(string.Format(" AND OH.ORG_ID IN ({0})", txtHidOrg.Value));
        }
        else
        {
            return;
        }

        if (ddlChains.SelectedValue != string.Empty)
        {
            sb.Append(" And CHAINS.ID = '" + ddlChains.SelectedValue + "' ");
        }
        if (ddlChannel.SelectedValue != string.Empty)
        {
            sb.Append(" AND C.LOCAL_LEVEL1_CODE =  '" + ddlChannel.SelectedValue + "'  ");
        }
        if (ddlUser.SelectedValue != string.Empty)
        {
            sb.Append(" AND OH.person_id =(select person_id from users where users.id='" + ddlUser.SelectedValue + "')  ");
        }
        if (txtCode.Text != string.Empty)
        {
            sb.Append("   AND (C.[CODE] LIKE '%" + txtCode.Text.Trim() + "%' or C.[NAME] LIKE '%" + txtCode.Text.Trim() + "%' or CI.[ADDRESS_LINE] like  '%" + txtCode.Text.Trim() + "%' "
                + " or C.default_ship_to_code LIKE '%" + txtCode.Text.Trim() + "%'  or  "
                + " CI.telephone LIKE '%" + txtCode.Text.Trim() + "%' or  CI.fax LIKE '%" + txtCode.Text.Trim() + "%' "
                + " )    ");
        }
        //针对客户ID的查询
        if (customerid != "")
        {
            sb.Append(customerid);
        }
        if (txtStart.Text != string.Empty)
        {
            sb.Append(" AND DATEDIFF(DD,dbo.[GetDateTimeByBigint](OH.ORDER_DATE),'" + DateTime.Parse(txtStart.Text).ToShortDateString() + "')<=0 ");
        }
        if (txtEnd.Text != string.Empty)
        {
            sb.Append(" AND DATEDIFF(DD,dbo.[GetDateTimeByBigint](OH.ORDER_DATE),'" + DateTime.Parse(txtEnd.Text).ToShortDateString() + "')>=0 ");
        }
        if (ddlStatus.SelectedValue != string.Empty)
        {
            sb.Append(" AND  OH.STATUS='" + ddlStatus.SelectedValue + "'  ");
        }
        else
        {
            sb.Append(" AND  OH.STATUS<>'" + ((int)EOderStatus.已取消).ToString() + "'  ");
        }
        if (txtOrderNo.Text != string.Empty)
        {
            sb.Append(" AND OH.ORDER_NO LIKE '%" + txtOrderNo.Text + "%' ");
        }
        if (this.ddlOrderType.SelectedValue != string.Empty)
        {
            sb.Append(" AND  OH.OrderType='" + ddlOrderType.SelectedValue + "'  ");
        }
        if (this.drpCancelled.SelectedValue != string.Empty)
        {
            //有效
            sb.Append(string.Format(" AND OH.CANCELLED='{0}' ", drpCancelled.SelectedValue));
        }
        if (ddlOrderForm.SelectedValue != string.Empty)
        {
            if (ddlOrderForm.SelectedValue == "0")
                sb.Append(" AND OH.ORDER_FORM IS NULL");
            else
                sb.Append(string.Format(" AND OH.ORDER_FORM='{0}' ", ddlOrderForm.SelectedValue));
        }
        sb.Append(" AND (USER_ID=" + MyStateManager.UserID + " or USER_ID in(select ID from USERS where person_id in(select ID from PERSONS where MANAGER_ID=" + MyStateManager.PersonID + " ))) ");
        DataSet ds = OrderHeaderManager.SearchOrderList(MyStateManager.DomainID, sb.ToString());
        if (ds != null && ds.Tables.Count > 0)
        {
            gvChannelType.DataSource = ds.Tables[0];
            gvChannelType.DataBind();
        }

    }

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        customerid = "";
        BindGrid();
        SaveConditions();
    }

    public void GridViewToolbarUserControl1_OnGVTBSetColumnsButtonEvent(object sender, EventArgs e)
    {
        BindGrid();
    }

    protected void gvChannelType_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvChannelType.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int rowCount = gvChannelType.Columns.Count;
            if (e.Row.Cells[rowCount - 1].Text.IndexOf("Y") > -1)
            {
                e.Row.Cells[rowCount - 1].Text = "<font size='3' color='red'>×</font>";
            }
            else
            {
                if (e.Row.Cells[rowCount - 1].Text.IndexOf("N") > -1)
                {
                    e.Row.Cells[rowCount - 1].Text = "<font size='3' color='green'>√</font>";
                }
            }
        }
    }
    protected void SaveConditions()
    {
        string pagename = "order_list";
        Session[pagename + "ddluser"] = ddlUser.SelectedValue;
        Session[pagename + "ddlordertype"] = ddlOrderType.SelectedValue;
        Session[pagename + "ddlchains"] = ddlChains.SelectedValue;
        Session[pagename + "txtstart"] = txtStart.Text;
        Session[pagename + "txtend"] = txtEnd.Text;
        Session[pagename + "txtcode"] = txtCode.Text;
        Session[pagename + "ddlchannel"] = ddlChannel.SelectedValue;
        Session[pagename + "ddlstatus"] = ddlStatus.SelectedValue;
        Session[pagename + "txtorderno"] = txtOrderNo.Text;
        Session[pagename + "drpcancelled"] = drpCancelled.SelectedValue;
        Session[pagename + "isactive"] = "1";

    }
    protected void LoadConditions()
    {
        string pagename = "order_list";
        if (Session[pagename + "isactive"] != null && Session[pagename + "isactive"].ToString() == "1")
        {
            try
            {
                ddlUser.SelectedValue = Session[pagename + "ddluser"].ToString();
                ddlOrderType.SelectedValue = Session[pagename + "ddlordertype"].ToString();
                ddlChains.SelectedValue = Session[pagename + "ddlchains"].ToString();
                txtStart.Text = Session[pagename + "txtstart"].ToString();
                txtEnd.Text = Session[pagename + "txtend"].ToString();
                txtCode.Text = Session[pagename + "txtcode"].ToString();
                ddlChannel.SelectedValue = Session[pagename + "ddlchannel"].ToString();
                ddlStatus.SelectedValue = Session[pagename + "ddlstatus"].ToString();
                txtOrderNo.Text = Session[pagename + "txtorderno"].ToString();
                drpCancelled.SelectedValue = Session[pagename + "drpcancelled"].ToString();
            }
            catch
            {
            }
            Session[pagename + "isactive"] = "0";
        }

    }

    private void Bindchains()
    {
        ddlChains.Items.Clear();

        DataTable dt = new ChainManager().GetCourseTable(MyStateManager.DomainID, txtHidOrg.Value);
        foreach (DataRow row in dt.Rows)
        {
            this.ddlChains.Items.Add(new ListItem(row["DESCRIPTION"].ToString(), row["ID"].ToString()));
        }

        ddlChains.Items.Insert(0, new ListItem("--所有--", ""));

    }

    protected void SelectPersons(object sender, EventArgs e)
    {
        if (ddlUser.SelectedIndex == 0)
        {
            Bindchains();
        }
        else
        {
            ddlChains.Items.Clear();
            //获取当前业务员ID

            DataTable dt = new ChainManager().GetChainsByUser(decimal.Parse(ddlUser.SelectedValue));
            foreach (DataRow row in dt.Rows)
            {
                this.ddlChains.Items.Add(new ListItem(row["DESCRIPTION"].ToString(), row["ID"].ToString()));
            }

            ddlChains.Items.Insert(0, new ListItem("--所有--", ""));

        }

    }


    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        //OrgHelper.BindChiansDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlChains);
        //OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlUser);


        Bindchains();
        ddlUser.Items.Clear();

 

        //判断当前的人所在的部门是不是最小的一级org
        var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        if (data.Rows.Count != 1)
        {
            if (!string.IsNullOrEmpty(txtHidUsers.Value))
            {
                string[] options2 = txtHidUsers.Value.Split('∮');
                for (int i = 0; i < options2.Length; i++)
                {
                    string[] item2 = options2[i].Split('∞');
                    ddlUser.Items.Add(new ListItem(item2[1], item2[0]));
                }
            }
            ddlUser.Items.Insert(0, new ListItem("--所有--", ""));
        }
        else
        {
            Person person = new PersonManager().Load(MyStateManager.PersonID);
            ddlUser.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
        }
       
        


    }

}
